$(function()
{
    // 获取国家列表
    function get_country()
    {
        $.ajax({
            url: ajax_request_domain + '/base/customs_country_list',
            type: 'post',
            dataType: 'json',
            beforeSend: (xhr) => {
                xhr.setRequestHeader("token", getLocalStorage('token'));
            },
            success: function (res) {
                if (res.code === 1) {
                    let html = '';
                    $.each(res.data, function (index, item) {
                        html += '<li data-value="'+ item.id + '">' + item.name + '</li>';
                    });
                    $('.main_con > .wide > .new_select > .higer_box > .choose > .business_country ul[name=TradeCountry]').html(html);
                }
                if (res.code === 0)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close(result.msg, 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    })
                }
            },
            error: function (result) {
                if (result.status === 500)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close('System error, please try again later', 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    })
                    return false;
                }
                if (result.status === 401)
                {
                    themes_obj.loginBox('index_type');
                    return false
                }
                else if (result.status  === 403)
                {
                    themes_obj.upgradeBox('index_type');
                    return false;
                }
            }
        });
    }
    get_country();
    // 加载热搜关键词
    function get_hot_keywords()
    {
        $.ajax({
            url: ajax_request_domain + '/base/get_hot_keywords?sellerType='+$('input[name=sellerType]').val(),
            method: 'get',
            beforeSend: (xhr) => {
                xhr.setRequestHeader("token", getLocalStorage('token'));
            },
            success: function (result) {
                if (result.code === 1) {
                    const data = result.data;
                    let topHtml = '';
                    let bottomHtml = '';
                    // 顶部搜索框,底部推荐
                    $.each(data, function (index, item) {
                        topHtml += '<a class="list_keywords" href="' + item.url + '" data-value="' + item.keywords + '" alt="' + item.keywords + '">' + item.keywords + '</a>';
                        bottomHtml += '<a class="item" href="' + item.url + '">';
                        bottomHtml += ' <div class="rank">' + (index+1) + '</div>';
                        bottomHtml += ' <div class="title">' + item.keywords + '</div>';
                        bottomHtml += '</a>';
                    });
                    $('.search.boxs .tuijian').append(topHtml);
                    $('.main_con .middle_area .hot_keywords .list').html(bottomHtml);
                }
                if (result.code === 0)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close(result.msg, 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    });
                    return false;
                }
            },
            error: function (result) {
                if (result.status === 500)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close('System error, please try again later', 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    })
                    return false;
                }
                if (result.status === 401)
                {
                    themes_obj.loginBox('index_type');
                    return false
                }
                else if (result.status  === 403)
                {
                    themes_obj.upgradeBox('index_type');
                    return false;
                }
            }
        });
    }
    get_hot_keywords();
    // 已选内容展示
    function has_choose_html()
    {
        let new_r_btn = '';
        $('#country_list input:checked,.chooses input:checked').each(function()
        {
            if ($(this).attr('id') == 'ChooseCountry1')
            {
                new_r_btn += '<div class="btn" attr-flag="1" attr-id="' + $(this).attr('id') + '">' + $(this).next().html() + '</div>'
            }
            else
            {
                new_r_btn += '<div class="btn close" attr-flag="1" attr-id="' + $(this).attr('id') + '">' + $(this).next().html() + '<i></i></div>'
            }
        });
        $('.main_con .left_side .filter_box .container .item input[type=radio]').each(function()
        {
            if ($(this).parents('.item').hasClass('current'))
            {
                if ($(this).attr('id') != 'ImportTimesField1' && $(this).attr('id') != 'ImportTimesField3' && $(this).attr('id') != 'ImportTimes1' && $(this).attr('id') != 'ImportTimes3' && $(this).attr('id') != 'TradeCountry1')
                {
                    new_r_btn += '<div class="btn close" attr-flag="2" attr-id="' + $(this).attr('id') + '">' + $(this).next().html() + '<i></i></div>'
                }
            }
        });

        // 高级搜索
        $('.main_con .new_select .higer_box .choose input').each(function() {
            if ($(this).attr('name') !== 'TradeCountry2' && $(this).val() && $(this).val() !== '0' && $(this).val() !== 0 && $(this).val() !== 'all') {
                let valText = '';
                if ($(this).attr('name') === 'foreign_port' || $(this).attr('name') === 'local_port') {
                    new_r_btn += '<div class="btn close" attr-flag="5" attr-name="' + $(this).attr('name') + '">' + $(this).val() + '<i></i></div>';
                } else if ($(this).attr('name') === 'business_date') {
                    valText = $('.business_date_val_text').html();
                    new_r_btn += '<div class="btn close" attr-flag="3" attr-name="' + $(this).attr('name') + '">' + valText + '<i></i></div>';
                } else {
                    valText = $('input[name="TradeCountry2"]').val();
                    new_r_btn += '<div class="btn close" attr-flag="4" attr-name="' + $(this).attr('name') + '">' + valText + '<i></i></div>';
                }
            }
        });

        $('.has_choose .r_list').html(new_r_btn);
    }
    has_choose_html();
    let list_timer = '';
    function list_fun(reload = 0, reloadtimes = 0)
    {
        // ajax请求获取列表
        var path = ajax_request_domain + '/customsCompany/customs_company_list';
        var params = $('#search_form').serialize();
        // 热门国家
        let hot_country = '';
        if (!$('#ChooseCountry1').is(':checked')) {
            let arr = [];
            $("input[name='hot_country[]']:checked").each(function (index, item) {
                arr.push($(item).val());
            });
            hot_country = arr.join(',');
        }
        if (hot_country) {
            params += '&hot_country=' + hot_country;
        }
        // 从中国采购
        if ($("input[name='from_china_supplier']").is(':checked')) {
            params += '&from_china_supplier=1';
        }
        // 高交易量
        if ($("input[name='high_business_num']").is(':checked')) {
            params += '&high_business_num=1';
        }
        // 近期有交易
        if ($("input[name='last_have_business']").is(':checked')) {
            params += '&last_have_business=1';
        }
        // 交易时间
        const business_date = $("input[name='business_date']").val();
        if (business_date && business_date !== 'all') {
            params += '&business_date=' + business_date;
        }
        // 交易次数
        const business_times = $("input[name='business_times']").val();
        if (business_times && business_times !== 'all') {
            params += '&business_times_type=' + business_times;
            if (business_times === 'diy') {
                const business_times_min = $("input[name='business_times_min']").val();
                const business_times_max = $("input[name='business_times_max']").val();
                params += '&business_times_value=' + business_times_min + ',' + business_times_max;
            }
        }
        // 采购区域
        const business_country = $("input[name='business_country']").val();
        if (business_country) {
            params += '&business_country=' + business_country;
        }
        // 出口港
        const foreign_port = $("input[name='foreign_port']").val();
        if (foreign_port) {
            params += '&foreign_port=' + foreign_port;
        }
        // 进口港
        const local_port = $("input[name='local_port']").val();
        if (local_port) {
            params += '&local_port=' + local_port;
        }


        // 恢复加载状态
        $('.main_con .middle_area .match span').addClass('load').html('<div class="dot-stretching"></div>');
        $('.main_con .middle_area .content').html($('.restPageListContent').html());
        $('#turn_page').html('');

        clearTimeout(list_timer);
        $.ajax({
            url: path,
            type: 'post',
            dataType: 'json',
            data: params,
            beforeSend: (xhr) => {
                xhr.setRequestHeader("token", getLocalStorage('token'));
            },
            success: function (result) {
                let old_size = $('#list_size').val();
                const _isLevel = parseInt($('#Level').val());
                const _isLogin = parseInt($('#AccountId').val());
                if (result.code === 1)
                {
                    let ret = result.data;
                    let new_html = '';
                    var NameAry = ["name", "title", "company", "detail_name"];
                    var UrlAry = ["detail_url", "detail_name_url", "company_detail_url", "focus_url"];
                    for (k in ret.list)
                    {
                        let this_v = ret.list[k];
                        let last_trade_products = '';
                        let last_trade_hs_code = '';
                        let KeywordsStr = '';
                        if (this_v['name'] && this_v['name'] !== 'N/A')
                        {
                            new_html += '<div class="bg_container">';
                            new_html += '	<div class="item">';
                            new_html += '	    <div class="top_msg">';
                            new_html += '		    <div class="left_msg selector">';
                            new_html += '               <input type="checkbox" name="select" value="' + this_v.seller_id + '">';
                            new_html += '		    </div>';
                            new_html += '		    <div class="right_msg">';
                            new_html += '			    <div class="' + NameAry[Math.floor(Math.random() * 4)] + '"><a class="' + UrlAry[Math.floor(Math.random() * 4)] + '" href="' + (this_v['url'] ? this_v['url'] : 'javascript:;') + '" target="_blank"' + '>' + this_v['name'] + '</a></div>';
                            // if (_isLogin == 1 || _isLogin == 2 || _isLogin == 3 || _isLogin == 9)
                            // {
                            //     new_html += '	        <div class="tips">' + lang_obj.clue.list.total_trade + '：' + this_v['Data']['import_times'] + '；' + lang_obj.clue.list.last_year_trade + '：' + this_v['Data']['years_times'] + '，' + lang_obj.clue.list.last_trade_time + this_v['Data']['last_time'] + '</div>'
                            // }
                            new_html += '			    <div class="tips">';
                            new_html += '				    <span><span class="i_out"><i class="icon_flag_middle flag_middle_' + this_v['country_code'] + '"></i></span>' + this_v['country_name'] + (ret.type === 1 ? lang_obj.header.supplier : lang_obj.header.buyer) + '</span>';
                            new_html += '			    </div>';
                            new_html += '		    </div>';
                            new_html += '	    </div>';
                            new_html += '		<div class="clear"></div>';
                            new_html += '		<div class="bottom_msg">';
                            new_html += '			<div class="new_box">';
                            new_html += '				<div class="right_box">	';
                            new_html += '					<span class="sec_copy">';
                            new_html += '						<span class="sec_name">' + lang_obj.trade.detail.products + '：</span>';
                            new_html += '						<span class="sec_value arial">';
                            last_trade_products = this_v['product'];
                            if (ret.request['Keywords'] != '')
                            {
                                last_trade_products = last_trade_products.replaceAll(ret.request['Keywords'], '<em>' + ret.request['Keywords'] + '</em>')
                                // for (k1 in result.msg['KeywordsAry'])
                                // {
                                //     last_trade_products = last_trade_products.replaceAll(result.msg['KeywordsAry'][k1], '<em>' + result.msg['KeywordsAry'][k1] + '</em>')
                                // }
                            }
                            new_html += last_trade_products;
                            new_html += '				        </span>';
                            new_html += '					</span>';
                            new_html += '					<span class="sec_copy">';
                            new_html += '						<span class="sec_name">' + lang_obj.clue.list.customs_code + '：</span>';
                            new_html += '						<span class="sec_value">';
                            last_trade_hs_code = this_v['hs_code'].toString();
                            // if ($('#CId').val() > 0 && result.msg['Keywords'] != '' && result.msg['Type'] == '2')
                            // {
                            //     for (k1 in result.msg['KeywordsAry'])
                            //     {
                            //         last_trade_hs_code = last_trade_hs_code.replaceAll(result.msg['KeywordsAry'][k1], '<em>' + result.msg['KeywordsAry'][k1] + '</em>')
                            //     }
                            // }
                            new_html += last_trade_hs_code;
                            new_html += '				        </span>';
                            new_html += '					</span>';
                            new_html += '				</div>';
                            // if ($('#CId').val() > 0 && result.msg['Keywords'] != '' && result.msg['Type'] != '1')
                            // {
                            //     new_html += '				<div class="word blod w"><span class="is_show">' + lang_obj.clue.list.keyword_match_trade.replace('%keyword%', KeywordsStr) + '</span><div>' + this_v['Data']['trade_count'] + '<span>' + lang_obj.clue.detail.pen + '</span></div></div>'
                            // }
                            new_html += '				<div class="word blod"><span class="is_show">' + lang_obj.clue.list.trade_total_nums + '</span><div>' + this_v['business_total'] + '<span>' + lang_obj.clue.detail.pen + '</span></div></div>';
                            new_html += '				<div class="btn">';
                            new_html += '	                <a target="_blank" class="collect2 ' + UrlAry[Math.floor(Math.random() * 4)] + '" href="' + this_v['url'] +'" target="_blank"' + '>' + lang_obj.clue.list.view_detail + '</a>';
                            new_html += '	                <a class="collect2 save_btn ' + ((this_v['is_collect'] === undefined || !this_v['is_collect']) ? 'favorite' : 'cancel_save') + '" href="javascript:;"><i></i><span>' + ((this_v['is_collect'] === undefined || !this_v['is_collect']) ? lang_obj.clue.list.add_to_favourite : lang_obj.clue.list.added_to_favourite) + '</span></a>';
                            new_html += '				</div>';
                            new_html += '			</div>';
                            new_html += '		</div>';
                            new_html += '	</div>';
                            new_html += '</div>'
                        }
                    }
                    if (ret && new_html == '')
                    {
                        let consultant = ret.contact;
                        new_html = '<div class="list_empty bg_container">';
                        new_html += '<div class="img">';
                        new_html += '<img src="/assets/site_resource/image/list_empty.png">';
                        let keywork = $("#search_form input[name=Keywords]").val();
                        if (keywork)
                        {
                            let no_match = lang_obj.clue.list.no_match_keywork;
                            no_match = no_match.replace('%keywork%', keywork);
                            no_match = no_match.replace('%role%', ret.type === 1 ? lang_obj.header.supplier : lang_obj.header.buyer);
                            let chooseText = '';
                            switch ($("input[name='collection_type']").val()) {
                                case '0' : {chooseText = '产品名称';break;}
                                case '1' : {chooseText = '公司名称';break;}
                                case '2' : {chooseText = 'HS编码';break;}
                            }
                            no_match = no_match.replace('%condition%', chooseText);
                            new_html += '<span>' + no_match + '</span>'
                        }
                        else
                        {
                            new_html += '<span>' + lang_obj.clue.list.no_match_threads + (ret.type === 1 ? lang_obj.header.supplier : lang_obj.header.buyer) + '</span>'
                        }
                        new_html += '</div>';
                        var date = new Date;
                        if (date.getDay() == 0 || date.getDay() == 6 || date.getHours() > 18 || date.getHours() < 9)
                        {
                            new_html += '<div class="consultant_box">';
                            new_html += '<div class="c_box_content">';
                            new_html += '<div class="c_box_title">' + lang_obj.clue.list.consultant_title + '<span>' + lang_obj.clue.list.consultant + '</span></div>';
                            new_html += '<div class="c_box_desc">' + lang_obj.clue.list.consultant_desc + '</div>';
                            new_html += '<div class="c_box_phone line">' + lang_obj.clue.list.consultant_phone + ':<span>' + consultant.mobile + '</span></div>';
                            new_html += '<div class="c_box_email line">' + lang_obj.clue.list.consultant_email + ':<span>nina@ueedata.com</span></div>';
                            new_html += '</div>';
                            new_html += '<div class="c_box_qrcode">';
                            new_html += '<div class="qrcode"><img src="' + consultant.qrcode + '" alt="' + consultant.name + '"></div>';
                            new_html += '<div class="c_q_desc">' + lang_obj.clue.list.qrcode_desc + '</div>';
                            new_html += '</div>';
                            new_html += '</div>';
                        }
                        else
                        {
                            new_html += '<div class="consultant_box_new">';
                            new_html += '<div class="title">' + lang_obj.clue.list.consultant_new_title + '</div>';
                            new_html += '<input type="button" class="btn_contact" value="' + lang_obj.clue.list.consultant_new_btn + '">';
                            new_html += '</div>';
                        }
                        new_html += '</div>';
                    }
                    else
                    {
                        if ($('#AccountId').val() == 0 || $('#Level').val() == 0)
                        {
                            $('#turn_page').addClass('level');
                        }
                        $('#turn_page').html(ret['page']);
                    }
                    if (new_html)
                    {
                        $('.main_con .middle_area .content').html(new_html);
                        // if ($('#CId').val() > 0 && result.msg['is_filter'])
                        // {
                        //     let noViewHtml = themes_obj.noViewBox($('#AccountId').val(), 'listdata', result.msg['list_size'], Role == 1 ? lang_obj.global.supplier : lang_obj.global.buyer);
                        //     $('.main_con .middle_area .content').addClass('no_view').append(noViewHtml);
                        //     let bottom_len = $(".main_con .middle_area .content.no_view").outerHeight();
                        //     if (bottom_len > $('.no_view_tip_box').outerHeight())
                        //     {
                        //         console.log($('.no_view_tip_box').outerHeight());
                        //         $('.no_view_tip_box').css({
                        //             top: '60px',
                        //             bottom: 'auto'
                        //         }).css('transform', 'translate(-50%,0%)');
                        //     }
                        // }
                    }
                    $('#list_size').val(ret.total);
                }
                else if (result.code === 0)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close(ret.msg, 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    });
                }
                else
                {
                    if (reloadtimes < 3) {
                        list_timer = setTimeout(function()
                        {
                            list_fun(0, reloadtimes+1);
                        }, 2000);
                    }
                }
                if (result.data.list.length)
                {
                    $('.main_con .middle_area .match span').removeClass('load').html(result.data.total);
                }
            },
            error: function (result) {
                if (result.status === 500)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close('System error, please try again later', 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    });
                    return false;
                }
                if (result.status === 401)
                {
                    themes_obj.loginBox('index_type');
                    return false;
                }
                else if (result.status === 403)
                {
                    themes_obj.upgradeBox('index_type');
                    return false;
                }
            }
        });
    }

    // 分页点击
    $('#turn_page,.alert_turn_page').on('click','a',function() {
        let page = $(this).data('page');
        if ($(this).parents('.jump').length) {
            page = $('input[name="jump_page"]').val();
            if (page == '' || page == undefined || page == 'undefined' || isNaN(page) || page <= 0 || page > parseInt($('input[name="jump_page"]').attr('max'))) {
                page = 1;
            }
        }

        // 滚动到列表顶部
        $('html, body').animate({
            scrollTop: $('.main_con > .wide > .middle_area').offset().top
        }, 500);

        $('#search_form input[name="page"]').val(page);
        list_fun();
    });

    $(document).on('ready',function () {
        $('#search_form input[name="page"]').val(1);
        list_fun();
    });
    // 搜索类型切换
    $('#banner').on('click', '.fiter_item', function()
    {
        let _thisChange = parseInt($(this).data('change')),
            _thisParentDataName = $(this).parents('.fiter_change').data('name');

        $('.search_tips_alert').hide();
        if (_thisParentDataName)
        {
            if (_thisParentDataName == 'collection_type' && ((_thisChange == 2 && zuoooo_config.Permit.ability.indexOf('hs_filter') == -1) || (_thisChange == 1 && zuoooo_config.Permit.ability.indexOf('company_filter') == -1)))
            {
                if (parseInt($('#AccountId').val()) == 0)
                {
                    themes_obj.loginBox('index_type');
                    return false;
                }
                else
                {
                    themes_obj.upgradeBox('index_type');
                    $('.global_alert_upgrade .upgrade_level_box_new input[value=13]').parents('.level_item').click();
                    return false;
                }
            }
            else
            {
                $('#banner .search').find(`input[name=${_thisParentDataName}]`).val(_thisChange);
                if ($(this).parents('.fiter_select').length)
                {
                    $('#banner .fiter_select').removeClass('show');
                    $('#banner .fiter_name').html($(this).text())
                }
                if (_thisParentDataName == 'collection_type')
                {
                    $(this).addClass('current').siblings().removeClass('current');
                    let _thisHtml = $(this).data('html');
                    if ($(window).width() <= 1024)
                    {
                        _thisHtml = _thisHtml.split('，')[0];
                    }
                    if (zuoooo_config.lang == 'en')
                    {
                        _thisHtml = lang_obj.trade.detail.p_choose + ' ' + $(this).text();
                        if ($(window).width() <= 1024)
                            _thisHtml = 'Enter keywords';
                    }
                    $('#banner .search form .input_box_content .fiter .fiter_select').each(function()
                    {
                        $(this).find("li").find("span").removeClass("fiter_select_li_choose").addClass("fiter_select_li_no_choose")
                    });
                    $(this).find("span").addClass("fiter_select_li_choose");
                    $('#banner .search form .input input').attr('placeholder', _thisHtml);
                }
            }
        }
    });
    // 搜索点击
    let dig_click;
    $('#banner .search form .dig').click(function()
    {
        // if (parseInt($('#AccountId').val()) == 0)
        // {
        //     themes_obj.loginBox('index_type');
        //     return false
        // }
        // themes_obj.recordUserModel('Search');
        var $this = $(this).parents('form');
        clearTimeout(dig_click);
        dig_click = setTimeout(function()
        {
            var para = (window.location.search).replace('?', '');
            let f = ks = o = series = group = s = c = '';
            if ($this.find('input[name=collection_type]').val() != 1 && $this.find('input[name=Keywords]').val() != '')
            {
                let reg = /\s(co.,ltd|ltd|co.|co|corp.|c.v.|pte.|sdn.bhd|s.r.o.|s.r.l.|s.a.r.l.|s.p.a.|k.k.|y.k|a\/s|a.l|c.de.rl|edms.bpk|i.s|k.s|inc|bv|nv|sa|ag|mfy|gmbh|bhd|llp|plc|est|fzc|fzco|fze|llc|jsc|ojsc|ab|oy|pt|tbk|pte|pvt|pty|bd|ao|as|av|ca|cia|cie|cv|ets|ges|hb|indecom|is|kb|kg|kk|ltda|lte|mbh|mij|nl|npl)$/i;
                if (reg.test($this.find('input[name=Keywords]').val()))
                {
                    $('.search_tips_alert').show();
                    return false;
                }
            }
            if (para != '')
            {
                var ary = para.split('&');
                for (i = 0; i < ary.length; i++)
                {
                    var v = ary[i].split('=');
                    if (v[0] == 'f' && v[1] != '')
                    {
                        f = '&' + v[0] + '=' + v[1];
                    }
                    else if (v[0] == 'k' && v[1] != '')
                    {
                        ks = '&' + v[0] + '=' + v[1];
                    }
                    else if (v[0] == 'o' && v[1] != '')
                    {
                        o = '&' + v[0] + '=' + v[1];
                    }
                    else if (v[0] == 'series' && v[1] != '')
                    {
                        series = '&' + v[0] + '=' + v[1];
                    }
                    else if (v[0] == 's' && v[1] != '')
                    {
                        s = '&' + v[0] + '=' + v[1];
                    }
                    else if (v[0] == 'c' && v[1] != '')
                    {
                        c = '&' + v[0] + '=' + v[1];
                    }
                }
            }
            if ($this.find('input[name=collection_type]').val() == 2 && $this.find('input[name=Keywords]').val() != '' && $this.find('input[name=Keywords]').val().length < 6)
            {
                global_obj.win_alert_auto_close(lang_obj.banner.hs_pla, 'fail', 2000, undefined, 0);
                return false;
            }
            if ($this.find('input[name=Keywords]').val() == '')
            {
                global_obj.new_win_alert(lang_obj.user.index.keyword_search, function()
                {
                    global_obj.div_mask(1);
                }, 'alert', 0, 'none');
                return false;
            }

            $('#search_form input[name="page"]').val(1);
            list_fun();

            return false;
        }, 300);
    });
    // 登录弹窗关闭
    $('.user_login_box .close').on('click',function () {
        $('#div_mask').click();
    });
    // 热词点击
    $('#banner .tuijian a.list_keywords').on('click', function()
    {
        $('#banner .search form input[name=Keywords]').val($(this).data('value'));
        $('#search_form input[name="page"]').val(1);
        list_fun();
    });
    // 热门国家点击
    $('.choose_box #country_list').on('click', '.item', function()
    {
        if (zuoooo_config.Permit.ability.indexOf('country_filter') == -1)
        {
            if ($('#AccountId').val() == 0)
            {
                themes_obj.loginBox('list_country', 'search-country');
                return false;
            }
            else
            {
                themes_obj.upgradeBox('country');
                return false;
            }
        }
        else
        {
            if ($(this).hasClass('all_item'))
            {
                $(this).parents('#country_list').find("input[name='hot_country[]']").prop('checked', false);
                $(this).parents('#country_list').find('input[type=checkbox]').removeAttr('checked').parents(".item.current").removeClass("current")
            }
            else
            {
                if ($(this).parents('#country_list').find("input[name='hot_country[]']:checked").length) {
                    $('#ChooseCountry1').prop('checked',false);
                } else {
                    $('#ChooseCountry1').prop('checked',true);
                }
            }
            $(this).toggleClass('current');

            has_choose_html();
            setTimeout(() =>
            {
                load_checked_length();
                if ($(window).width() <= 1024)
                {
                    // $('#banner .search form input[name=is_go]').val('1');
                    $('#search_form input[name="page"]').val(1);
                    list_fun();
                }
            }, 50);
        }
    });
    // 高级筛选
    // 子选项点击事件
    $(document).on("click",'.main_con .new_select .higer_box .rows_item .input_position li',function(){
        console.log('点击了');
        if (zuoooo_config.Permit.ability.indexOf('country_filter') == -1)
        {
            if ($('#AccountId').val() == 0)
            {
                themes_obj.loginBox('business_times');
                return false;
            }
            else
            {
                themes_obj.upgradeBox('business_times');
                return false;
            }
        }

        $(this).addClass('cur').siblings().removeClass('cur');
        const inputName = $(this).parents('ul').data('name');
        console.log($('.' + inputName + ' input[name="' + inputName + '"]'));
        $('.' + inputName + ' input[name="' + inputName + '"]').val($(this).data('value'));
        $('.' + inputName + ' .rows_name_sel').text($(this).text());
        $('.' + inputName + ' input[name="TradeCountry2"]').val($(this).text());

        if($(this).hasClass('reslef')){
            $('.main_con .new_select .higer_box .rows_custom').show();
            $('.main_con .new_select .higer_box .choose').addClass('cur');
        }else{
            $('.main_con .new_select .higer_box .rows_custom').hide();
            $('.main_con .new_select .higer_box .choose').removeClass('cur');
        }

        has_choose_html();
        list_fun();
    });
    // 监听采购区域输入框没有内容
    $('.main_con .new_select .higer_box .business_country input:last-child').on('input',function () {
        if ($(this).val() === '')
        $("input[name='business_country']").val('');
    });


    function fix_menu()
    {
        var start_h = parseFloat($('.main_con').offset().top),
            right_h = parseFloat($('.main_con .right_side .side_box').outerHeight()),
            end_h = parseFloat($('#footer').offset().top),
            scroll_h = $(window).scrollTop();
        var viewWidth = window.innerWidth;
        if (scroll_h > start_h && viewWidth > 1024)
        {
            $('.main_con').addClass('menu_fix');
            if (scroll_h > (end_h - right_h - 60))
            {
                let cut_h = scroll_h - (end_h - right_h - 60);
                $('.main_con .right_side .side_box').attr('style', 'transform: translate(0px, -' + cut_h + 'px);')
            }
            else
            {
                $('.main_con .right_side .side_box').removeAttr('style')
            }
        }
        else
        {
            $('.main_con .right_side .side_box').removeAttr('style');
            $('.main_con').removeClass('menu_fix')
        }
    }
    $(window).scroll(function()
    {
        fix_menu()
    });
    fix_menu();
    const AccountId = $('#AccountId').val();
    $('.main_con .right_side .li_box .li a').on('click', function()
    {
        if ($('#AccountId').val() == 0)
        {
            themes_obj.loginBox('list_history');
            return false;
        }
    });
    $('.main_con .new_select .higer_box .rows_name_sel').on("click",function(){
        $(this).next('.input_position').toggle();
        $(this).parents('.form_rows').siblings().find('.input_position').hide();
    });
    $(document).on("click", function(event) {
      var target = $(event.target);
      if (!target.is(".main_con .new_select .higer_box .rows_name_sel") && !target.parents().is(".main_con .new_select .higer_box .rows_name_sel")) {
        $(".main_con .new_select .higer_box .input_position").hide();
      }
    });

    $('.main_con .new_select .higer_box .name a').on("click",function(){
        if($(this).hasClass('cur')){
            $(this).removeClass('cur');
            $(this).html("展开 <img src=/assets/site_resource/image/user_more.png alt=>");
            $('.main_con .new_select .higer_box .choose').css("display","none");
        }else{
            $(this).addClass('cur');
            $(this).html("收起 <img src=/assets/site_resource/image/user_more.png alt=>");
            $('.main_con .new_select .higer_box .choose').css("display","flex");
        }
    })
    function load_checked_length()
    {
        let ckeck_size = 0;
        $('#filter_form input').each(function()
        {
            if ($(this).is(':checked'))
            {
                ckeck_size++;
            }
        });
        $('.left_side .lead_recommend .container input').each(function()
        {
            if ($(this).is(':checked'))
            {
                ckeck_size--;
            }
        });
        $('#country_list input').each(function()
        {
            if ($(this).is(':checked'))
            {
                ckeck_size++;
            }
        });
        $('.main_con .left_side .filter_condition .name span').html(ckeck_size);
        if ($(window).width() > 1024)
        {
            // $('#banner .search form input[name=is_go]').val('1');
            // $('#banner .search form .dig').click()
            has_choose_html();
            $('#search_form input[name="page"]').val(1);
            list_fun();
        }
    }
    let company_save_timer = '';
    $('.main_con').on('click', '.left_side .filter_condition .delete', function() {
        if ($('#Role').val() == 1)
        {
            window.location.href = '/supplier/';
        }
        else
        {
            window.location.href = '/buyer/';
        }
        return false;
        $('#filter_form input').each(function()
        {
            if ($(this).is(':checked'))
            {
                $(this).removeAttr('checked');
                $(this).parents('.item').removeClass('current')
            }
        });
        $('#filter_form input[name=MaxImportTimes]').val(0);
        load_checked_length()
    })
        .on('click', '.middle_area .content .item .favorite', function() {
        if ($('#AccountId').val() == 0)
        {
            themes_obj.loginBox('list_collect')
        }
        else
        {
            let _this = $(this);
            clearTimeout(company_save_timer);
            company_save_timer = setTimeout(function()
            {
                let this_parents = _this.parents('.item');
                if (this_parents.attr('saving') == 0)
                {
                    let cid = $('#CId').val();
                    let lid = this_parents.attr('lid');

                }
            }, 500)
        }
        return false;
    })
        // 线索推荐点击
        .on('click', '.new_select .choose_box.filter .chooses .item input', function() {
        if (zuoooo_config.Permit.ability.indexOf('search_filter') == -1)
        {
            let value = $(this).val();
            let regf = $(this).attr('regf');
            if ($('#AccountId').val() == 0)
            {
                themes_obj.loginBox(value, regf);
                return false
            }
            else
            {
                themes_obj.upgradeBox(value);
                return false
            }
        }
        else
        {
            if (!$(this).parents('.item').hasClass('current'))
            {
                $(this).parents('.item').addClass('current');
                let this_type = $(this).parents('.item').attr('attr-type');
                if (this_type == 'logistics')
                {
                    $('#search_form input[name=logistics]').val('1')
                }
                else
                {
                    $('.recommend_' + this_type).click()
                }
            }
            else
            {
                $(this).parents('.item').removeClass('current');
                let this_type = $(this).parents('.item').attr('attr-type');
                if (this_type == 'logistics')
                {
                    $('#search_form input[name=logistics]').val('0')
                }
                else
                {
                    $('.recommend_' + this_type).prop('checked', false).parents(".item.current").removeClass("current")
                }
            }
            setTimeout(() =>
                {
                    load_checked_length()
                }, 50)
        }
    })
        .on('click', '.middle_area .content .item .cancel_save', function() {
        if ($('#AccountId').val() == 0)
        {
            themes_obj.loginBox('list_collect')
        }
        else
        {
            let _this = $(this);
            let this_parents = _this.parents('.item');
            if (this_parents.attr('saving') == 1)
            {
                let cid = this_parents.attr('savingCId');
                let lid = this_parents.attr('lid');

            }
        }
        return false
    });

    if (($('#AccountId').val() == 0 || ($('#CId').val() > 0 && $('#Level').val() == 0 && zuoooo_config.Permit.ability.indexOf('search_list') >= 0)) && $('#page').val() > 1)
    {
        if ($('#AccountId').val() == 0)
        {
            themes_obj.loginBox('list_page')
        }
        else
        {
            themes_obj.upgradeBox('list_page')
        }
    }
    if ($(window).width() <= 1024)
    {
        $('.main_con .left_side .filter_box .container').on('change', '.item input[name=ImportTimesField]', function()
        {
            if ($(this).val() == 12)
            {
                if (!$('#filter_form .filter_box input[id=LeadsCheckbox3]').parents(".item").hasClass('current'))
                {
                    $('#filter_form .filter_box input[id=LeadsCheckbox3]').prop('checked', true).parents(".item").addClass("current")
                }
            }
            else
            {
                $('#filter_form .filter_box input[id=LeadsCheckbox3]').prop('checked', false).parents(".item.current").removeClass("current")
            }
        });
        $('.main_con .left_side .filter_box .container').on('change', '.item input[name=ImportTimes]', function()
        {
            if ($(this).val() == 100)
            {
                if (!$('#filter_form .filter_box input[id=LeadsCheckbox2]').parents(".item").hasClass('current'))
                {
                    $('#filter_form .filter_box input[id=LeadsCheckbox2]').prop('checked', true).parents(".item").addClass("current")
                }
            }
            else
            {
                $('#filter_form .filter_box input[id=LeadsCheckbox2]').prop('checked', false).parents(".item.current").removeClass("current")
            }
        });
        $('.main_con .left_side .filter_box .container').on('change', '.item input[name=TradeCountry]', function()
        {
            if ($(this).val() == 'CN')
            {
                if (!$('#filter_form .filter_box input[id=LeadsCheckbox1]').parents(".item").hasClass('current'))
                {
                    $('#filter_form .filter_box input[id=LeadsCheckbox1]').prop('checked', true).parents(".item").addClass("current")
                }
            }
            else
            {
                $('#filter_form .filter_box input[id=LeadsCheckbox1]').removeAttr('checked').parents(".item.current").removeClass("current")
            }
        })
    }
    $('.main_con .left_side .filter_box .container').on('change', '.item input[name=ImportTimes]', function()
    {
        let max = $(this).attr('max');
        if (!max)
            max = 0;
        $('#filter_form input[name=MaxImportTimes]').val(max)
    });
    $('.main_con .middle_area .match i').on('click', function()
    {
        if (zuoooo_config.Permit.ability.indexOf('search_filter') == -1 && zuoooo_config.Permit.ability.indexOf('country_filter') == -1)
        {
            if ($('#AccountId').val() == 0)
            {
                themes_obj.memberReminderBox('list_filter');
                return false
            }
            else
            {
                themes_obj.upgradeBox('adsearch');
                return false
            }
        }
        else
        {
            global_obj.div_mask();
            $('.main_con .left_side').addClass('current')
        }
    });
    $('.main_con .left_side .filter_condition .close').on('click', function()
    {
        global_obj.div_mask(1);
        $('.main_con .left_side').removeClass('current')
    });
    $('.main_con .left_side .filter_button').on('click', function()
    {
        $('#banner .search form input[name=is_go]').val('1');
        $('#banner .search form .dig').click()
    });
    $('.main_con .left_side .filter_box a.more[name=filter_condition],.main_con .new_select .choose_box.filter .more').on('click', function()
    {
        if (zuoooo_config.Permit.ability.indexOf('search_filter') == -1)
        {
            if ($('#AccountId').val() == 0)
            {
                let regf = $(this).parents('.filter_box').attr('regf');
                themes_obj.loginBox('list_filter', regf ? regf : 'search-filter');
                return false
            }
            else
            {
                themes_obj.upgradeBox('adsearch');
                return false
            }
        }
        else
        {
            global_obj.div_mask();
            $('.global_alert_box.alert_filter_condition').addClass('cur');
            filterSyncToAlert()
        }
    });
    $('.global_alert_box.alert_filter_condition .close').on('click', function()
    {
        if ($(window).width() > 1024)
            global_obj.div_mask(1);
        $('.global_alert_box.alert_filter_condition').removeClass('cur')
    });
    $('.global_alert_box.alert_filter_condition .radio_box input').on('click', function()
    {
        $(this).parents('.radio_box').addClass('current').siblings().removeClass('current')
    });
    $('.global_alert_box.alert_filter_condition .radio_box input[name=ImportTimes]').on('change', function()
    {
        let customBox = $('.global_alert_box.alert_filter_condition .rows_custom');
        $(this).val() == 'custom' ? customBox.show() : customBox.hide()
    });
    $('.global_alert_box.alert_filter_condition .form_buttom button[name=cancel]').on('click', function()
    {
        $('.global_alert_box.alert_filter_condition .close').trigger('click')
    });
    $('.global_alert_box.alert_filter_condition .form_buttom button[name=submit]').on('click', function()
    {
        alertSyncToFilter();
        if ($(window).width() > 1024)
            $('.global_alert_box.alert_filter_condition .close').trigger('click');
        load_checked_length();
        if ($(window).width() <= 1024)
        {
            $('#banner .search form input[name=is_go]').val('1');
            $('#banner .search form .dig').click()
        }
    });
    $('.global_alert_box.alert_filter_condition,.main_con .new_select .higer_box .rows_item').find('input[name=TradeCountry2]').on('click keyup', function(event)
    {
        event.stopPropagation();
        var flag = true;
        $('.input_position').hide();
        let value = $(this).val();
        let ul = $(this).next('.input_position');
        let length = 0;
        ul.find('li').each(function()
        {
            let text = $(this).text().toLowerCase();
            if (text.indexOf(value.toLowerCase()) == -1)
            {
                $(this).hide()
            }
            else
            {
                $(this).show();
                length++
            }
        });
        if (length > 0)
            ul.show();
        let fist_child;
        ul.find("li").each(function()
        {
            if ($(this).css('display') == 'list-item')
            {
                if (!fist_child)
                {
                    fist_child = $(this)
                }
            }
        });
        if (fist_child)
        {
            let li_country = fist_child.attr('data-country');
            let li_span_text = fist_child.find("span").html();
            $(this).parents('.input_box').find("input[name='TradeCountry']").val(li_span_text).attr('country', li_country)
        }
        else
        {
            $(this).parents('.input_box').find("input[name='TradeCountry']").val($(this).val()).attr('country', $(this).attr('country'))
        }
        $(document).bind("click", function(e)
        {
            var target = $(e.target);
            if (target.closest(ul).length == 0 && flag == true)
            {
                ul.hide();
                flag = false
            }
        });
        if (value.length == 0)
        {
            $(this).parents('.input_box').find('input:first-child').val('');
            // $(this).parents('.input_box').find('input[name="TradeCountry"]').val('').attr('country', '');
            event.preventDefault();
            return false;
        }
    });
    $('.global_alert_box.alert_filter_condition .input_position').on('click', 'li', function()
    {
        $(this).addClass('current').siblings().removeClass('current');
        $(this).parent().prev('input').val($(this).find('span:first').text()).attr('country', $(this).data('country'));
        $(this).parents('.input_box').find('input[name="' + $(this).parent().attr('name') + '"]').val($(this).find('span:first').text()).attr('country', $(this).data('country'));
        $('.global_alert_box.alert_filter_condition .input_position').hide()
    });
    let filterSyncToAlert = () =>
            {
                let alertForm = $('.global_alert_box.alert_filter_condition');
                alertForm.find('.radio_box.current').removeClass('current').find('input').prop('checked', false);
                alertForm.find('input[name=MinImportTimes], input[name=MaxImportTimes], input[name=TradeCountry], input[name=ExportPort], input[name=ImportPort]').val('');
                alertForm.find('input[name=TradeCountry]').attr('country', '');
                let filterForm = $('#filter_form');
                let date = filterForm.find('input[name=ImportTimesField]:checked').val();
                let times = filterForm.find('input[name=ImportTimes]:checked').val();
                let area = filterForm.find('input[name=TradeCountry]:checked').val();
                let exportPort = filterForm.find('input[name=ExportPort]:checked').val();
                let importPort = filterForm.find('input[name=ImportPort]:checked').val();
                if (date)
                    alertForm.find(`input[name=ImportTimesField][value='${date}']`).trigger('click');
                if (times)
                {
                    let value = times;
                    let maxInput = filterForm.find(`input[name=MaxImportTimes]`).val();
                    if (maxInput > 0)
                        value = 'custom';
                    alertForm.find('input[name=MinImportTimes]').val(times);
                    alertForm.find('input[name=MaxImportTimes]').val(maxInput);
                    if (!alertForm.find(`input[name=ImportTimes][value='${value}']`).length)
                        value = 'custom';
                    alertForm.find(`input[name=ImportTimes][value='${value}']`).trigger('click')
                }
                if (area)
                {
                    let country = filterForm.find('input[name=TradeCountry]:checked').next('label').text();
                    alertForm.find('input[name=TradeCountry]').val(country).attr('country', area);
                    alertForm.find('input[name=TradeCountry2]').val(country).attr('country', area)
                }
                if (exportPort)
                    alertForm.find('input[name=ExportPort]').val(exportPort);
                if (importPort)
                    alertForm.find('input[name=ImportPort]').val(importPort)
            };
    let alertSyncToFilter = () =>
            {
                let alertForm = $('.global_alert_box.alert_filter_condition');
                let date = alertForm.find('input[name=ImportTimesField]:checked').val();
                let times = alertForm.find('input[name=ImportTimes]:checked').val();
                let area = alertForm.find('input[name=TradeCountry]').val();
                let exportPort = alertForm.find('input[name=ExportPort]').val();
                let importPort = alertForm.find('input[name=ImportPort]').val();
                let filterForm = $('#filter_form');
                if (date)
                {
                    let input = filterForm.find(`input[name=ImportTimesField][value='${date}']`);
                    input.parents('.container').find('.item').removeClass('current');
                    input.prop('checked', true).parents('.item').addClass('current');
                    input.parents('.item').removeClass('hide')
                }
                if (times)
                {
                    if (times == 'custom')
                    {
                        let minImportTimes = parseInt(alertForm.find('input[name=MinImportTimes]').val());
                        let maxImportTimes = parseInt(alertForm.find('input[name=MaxImportTimes]').val());
                        if (isNaN(minImportTimes))
                            minImportTimes = 0;
                        if (isNaN(maxImportTimes))
                            maxImportTimes = 0;
                        if (minImportTimes >= maxImportTimes)
                            maxImportTimes = 0;
                        let minInput = filterForm.find(`input#ImportTimes4`);
                        let maxInput = filterForm.find(`input[name=MaxImportTimes]`);
                        if (maxImportTimes == 0)
                        {
                            minInput.next('label').text(`${lang_obj.clue.list.trade_greater_than}${minImportTimes}`)
                        }
                        else if (minImportTimes == 0)
                        {
                            minInput.next('label').text(`${lang_obj.clue.list.trade_less_than}${maxImportTimes}`)
                        }
                        else
                        {
                            minInput.next('label').text(`${minImportTimes}-${maxImportTimes}`)
                        }
                        maxInput.val(maxImportTimes);
                        filterForm.find(`input[name=ImportTimes]`).parents('.container').find('.item').removeClass('current');
                        minInput.prop('checked', true).parents('.item').addClass('current');
                        minInput.val(minImportTimes).attr('max', maxImportTimes).parents('.item').removeClass('hide')
                    }
                    else
                    {
                        filterForm.find(`input[name=MaxImportTimes]`).val('');
                        filterForm.find(`input[name=ImportTimes][value='${times}']`).parents('.container').find('.item').removeClass('current');
                        filterForm.find(`input[name=ImportTimes][value='${times}']`).prop('checked', true).parents('.item').addClass('current')
                    }
                }
                let value = area;
                let country = alertForm.find('input[name=TradeCountry]').attr('country');
                if (country)
                    value = country;
                let areaInput = filterForm.find(`input[name=TradeCountry][value='${value}']`);
                if (!areaInput.length)
                    filterForm.find('input#TradeCountry4').val(value).next('label').text(area).parents('.item').removeClass('hide');
                filterForm.find(`input[name=TradeCountry][value='${value}']`).parents('.container').find('.item').removeClass('current');
                filterForm.find(`input[name=TradeCountry][value='${value}']`).prop('checked', true).parents('.item').addClass('current');
                let exportPortInput = filterForm.find(`input[name=ExportPort][value='${exportPort}']`);
                if (!exportPortInput.length)
                    filterForm.find('input#ExportPort4').val(exportPort).next('label').text(exportPort).parents('.item').removeClass('hide');
                filterForm.find(`input[name=ExportPort][value='${exportPort}']`).parents('.container').find('.item').removeClass('current');
                filterForm.find(`input[name=ExportPort][value='${exportPort}']`).prop('checked', true).parents('.item').addClass('current');
                let ImportPortInput = filterForm.find(`input[name=ImportPort][value='${importPort}']`);
                if (!ImportPortInput.length)
                    filterForm.find('input#ImportPort4').val(importPort).next('label').text(importPort).parents('.item').removeClass('hide');
                filterForm.find(`input[name=ImportPort][value='${importPort}']`).parents('.container').find('.item').removeClass('current');
                filterForm.find(`input[name=ImportPort][value='${importPort}']`).prop('checked', true).parents('.item').addClass('current')
            };
    themes_obj.fixedRight({
        click: '.main_con .side_box .item.collect',
        target: '.fixed_collect',
        check: function()
        {
            if ($('#AccountId').val() > 0)
                return true;
            themes_obj.loginBox('list_collect');
            return false
        },
        submit: function()
        {
            let cid = $('#CId').val();
            let lid = [];
            let type = $('.fixed_collect select[name=type]').val();
            let cateid = $('.fixed_collect input[name=category]').attr('id');
            $('.main_con .middle_area .content .bg_container').each(function()
            {
                let id = $(this).find('.item').attr('lid');
                lid.push(id)
            });

        }
    });
    $('.fixed_collect input[name=category]').on('click keyup', function()
    {
        $('.input_position').hide();
        let value = $(this).val();
        let ul = $(this).next('.input_position');
        let length = 0;
        ul.find('li').each(function()
        {
            let text = $(this).text().toLowerCase();
            if (text.indexOf(value.toLowerCase()) == -1)
            {
                $(this).hide()
            }
            else
            {
                $(this).show();
                length++
            }
        });
        if (length > 0)
            ul.show();
        if (!value)
            $(this).attr('id', 0)
    });
    $('.fixed_collect .input_position li').on('click', function()
    {
        $(this).parent().prev('input').val($(this).text()).attr('id', $(this).data('id'));
        $('.fixed_collect .input_position').hide()
    });
    $('#country_list .recommend .more,.main_con .new_select .choose_box.country .more').on('click', function()
    {
        if (zuoooo_config.Permit.ability.indexOf('country_filter') == -1)
        {
            if ($('#AccountId').val() == 0)
            {
                themes_obj.loginBox('list_country', 'search-country');
                return false
            }
            else
            {
                themes_obj.upgradeBox('country');
                return false
            }
        }
        else
        {
            $('.new_abs_left').removeClass('cur');
            global_obj.div_mask();
            $('.global_fixed_right.country_box').addClass('current');
            $('#country_list .recommend .box .item').each(function()
            {
                let value = $(this).find('input').val();
                let isCheck = $(this).find('input').prop('checked');
                if (isCheck)
                {
                    $(`.global_fixed_right.country_box input[value='${value}']`).prop('checked', true).parents('label').addClass('cur')
                }
                else
                {
                    $(`.global_fixed_right.country_box input[value='${value}']`).prop('checked', false).parents('label').removeClass('cur')
                }
                check_is_has()
            })
        }
        return false
    });
    $('.global_fixed_right.country_box .title .close').on('click', function()
    {
        global_obj.div_mask(1);
        $('.global_fixed_right.country_box').removeClass('current')
    });
    $('.country_table .right_out span').on('click', function()
    {
        let strpos = $(this).html();
        $('.country_table .right_out span').removeClass('cur');
        $(this).addClass('cur');
        $('.country_table .left_out label').each(function()
        {
            let _this_html = $(this).find('span').attr('cn');
            if (strpos == _this_html)
            {
                $(this).show()
            }
            else
            {
                $(this).hide()
            }
        })
    }).eq(0).click();
    function check_is_has()
    {
        $('.country_table .right_out span').each(function()
        {
            let _this = $(this);
            let strpos = _this.html();
            let is_had = 0;
            $('.global_fixed_right .country_table label.cur').each(function()
            {
                let _this_html = $(this).find('span').attr('cn');
                if (strpos == _this_html)
                {
                    is_had++
                }
            });
            if (is_had > 0)
            {
                _this.addClass('has')
            }
            else
            {
                _this.removeClass('has')
            }
        })
    }
    check_is_has();
    $('.global_fixed_right').on('click', '.country_table label', function()
    {
        if ($(this).hasClass('all_item'))
        {
            if ($(this).hasClass('cur'))
            {
                $(this).removeClass('cur')
            }
            else
            {
                $(this).addClass('cur')
            }
            $('.item_box').find('label').removeClass('cur');
            $('.item_box').find('label input').removeAttr('checked')
        }
        else if ($(this).hasClass('continent_item'))
        {
            $('.all_item').removeClass('cur');
            if ($(this).hasClass('cur'))
            {
                $(this).removeClass('cur');
                $(this).next().each(function()
                {
                    $(this).find('label').removeClass('cur');
                    $(this).find('label input').removeAttr('checked')
                })
            }
            else
            {
                $(this).addClass('cur');
                $(this).next().each(function()
                {
                    $(this).find('label').addClass('cur');
                    $(this).find('label input').attr('checked', 'checked')
                })
            }
        }
        else
        {
            clickCountry($(this))
        }
        showCountryResult($(this))
    });
    function clickCountry(self)
    {
        $('.all_item').removeClass('cur');
        var continent_flag = true;
        if (self.hasClass('cur'))
        {
            self.removeClass('cur');
            self.find('input').removeAttr('checked');
            continent_flag = false
        }
        else
        {
            self.addClass('cur');
            self.find('input').attr('checked', 'checked');
            self.parents('.item_child_box').find('label').each(function()
            {
                if (!$(this).hasClass('cur') && continent_flag)
                {
                    continent_flag = false
                }
            })
        }
        if (continent_flag)
        {
            self.parents('.item_box').find('.continent_item').addClass('cur')
        }
        else
        {
            self.parents('.item_box').find('.continent_item').removeClass('cur')
        }
    }
    function showCountryResult(self)
    {
        if (self.hasClass('all_item') && self.hasClass('cur'))
        {
            $('.global_fixed_right.country_box .bottom_fix span.tips').hide();
            $('.global_fixed_right.country_box .bottom_fix span.global_tips').show()
        }
        else
        {
            $('.global_fixed_right.country_box .bottom_fix span.global_tips').hide();
            $('.global_fixed_right.country_box .bottom_fix span.tips').show()
        }
        $('.global_fixed_right.country_box .bottom_fix span i').text($('.global_fixed_right .country_table .item_child_box label.cur').length)
    }
    $('.global_fixed_right.country_box .bottom_fix .btn').on('click', function()
    {
        if (zuoooo_config.Permit.ability.indexOf('country_filter') == -1)
        {
            $('.global_fixed_right.country_box').removeClass('current');
            if ($('#AccountId').val() == 0)
            {
                themes_obj.loginBox('list_country', 'search-country');
                return false
            }
            else
            {
                themes_obj.upgradeBox('country');
                return false
            }
        }
        else
        {
            let _idNum = $('#country_list .item').length;
            $('.country_table .left_out .item_child_box label').each(function(index)
            {
                let _thisValue = $(this).find('input[name=Country\\[\\]]').val();
                let _thisName = $(this).find('span').html();
                _thisName = _thisName.split('（')[0];
                if ($(this).hasClass('cur'))
                {
                    _idNum = _idNum + 1;
                    if (!$(`#country_list input[value='${_thisValue}']`).length)
                    {
                        let add_html = `
					<div class="item current">
						<input id="checkbox${_idNum}" type="checkbox" hidden name="Country[]" value="${_thisValue}" checked />
						<label for="checkbox${_idNum}">${_thisName}</label>
					</div>
					`;
                        $('#country_list').append(add_html)
                    }
                    $(`#country_list input[value='${_thisValue}']`).prop('checked', true).parents('.item').addClass('current')
                }
                else
                {
                    $(`#country_list input[value='${_thisValue}']`).prop('checked', false).parents('.item').removeClass('current')
                }
            });
            global_obj.div_mask(1);
            $('.global_fixed_right.country_box').removeClass('current');
            setTimeout(() =>
                {
                    load_checked_length();
                    if ($(window).width() <= 1024)
                    {
                        $('#banner .search form input[name=is_go]').val('1');
                        $('#banner .search form .dig').click()
                    }
                }, 50)
        }
    });
    $('.country_table').find('input[name=Country2]').on('click keyup', function(event)
    {
        event.stopPropagation();
        var flag = true;
        $('.input_position').hide();
        let value = $(this).val();
        let ul = $(this).next('.input_position');
        let length = 0;
        ul.find('li').each(function()
        {
            let text = $(this).text().toLowerCase();
            if (text.indexOf(value.toLowerCase()) == -1)
            {
                $(this).hide()
            }
            else
            {
                $(this).show();
                length++
            }
        });
        if (length > 0)
            ul.show();
        let fist_child;
        $("ul[name='Country']").find("li").each(function()
        {
            if ($(this).css('display') == 'list-item')
            {
                if (!fist_child)
                {
                    fist_child = $(this)
                }
            }
        });
        if (fist_child)
        {
            let li_country = fist_child.attr('country');
            $("input[name='Country']").val(li_country)
        }
        else
        {
            $("input[name='Country']").val($(this).val())
        }
        $(document).bind("click", function(e)
        {
            var target = $(e.target);
            if (target.closest($('.input_position')).length == 0 && flag == true)
            {
                $('.input_position').hide();
                flag = false
            }
        });
        if (value.length == 0)
        {
            $(this).parents('.input_box').find('input[name="Country"]').val('');
            $('.all_item').show();
            $('.item_box').each(function()
            {
                $(this).find('.item_child_box label').each(function()
                {
                    $(this).show()
                });
                $(this).show()
            });
            event.preventDefault();
            return false
        }
    });
    $('.country_table .input_position').on('click', 'li', function()
    {
        $(this).addClass('current').siblings().removeClass('current');
        $(this).parent().prev('input').val($(this).text());
        $(this).parents('.input_box').find('input[name="' + $(this).parent().attr('name') + '"]').val($(this).attr('country'));
        var countryCode = $(this).attr('country');
        $('.item_child_box label').each(function()
        {
            if ($(this).find('input').val() == countryCode && !$(this).hasClass('cur'))
            {
                clickCountry($(this));
                showCountryResult($(this));
                return false
            }
        });
        $('.all_item').hide();
        $('.item_box').each(function()
        {
            var item_box_flag = true;
            $(this).find('.item_child_box label').each(function()
            {
                if ($(this).find('input').val() != countryCode)
                {
                    $(this).hide()
                }
                else
                {
                    item_box_flag = false
                }
            });
            if (item_box_flag)
            {
                $(this).hide()
            }
        });
        $('.country_table .input_position').hide()
    });
    $(window).scroll(function()
    {
        $('.input_position').hide()
    });
    // 收藏点击
    $('.content').on('click', '.collect2.save_btn', function()
    {
        var _self = $(this);
        let id = '';
        id = _self.parents('.bg_container').find("input[name='select']").val();

        let seller_type = 'importer';
        if (window.location.pathname === '/buyer')
        {
            seller_type = 'importer';
        }
        if (window.location.pathname === '/supplier')
        {
            seller_type = 'exporter';
        }

        $.ajax({
            url: ajax_request_domain + '/customsCompany/customs_company_collect',
            type: 'post',
            dataType: 'json',
            data: {
                seller_type: seller_type,
                company_ids: id
            },
            beforeSend: (xhr) => {
                xhr.setRequestHeader("token", getLocalStorage('token'));
            },
            success: function(result){
                if (result.code === 1) {
                    if (result.data === true) {
                        if (_self.hasClass('cancel_save')) {
                            _self.removeClass('cancel_save');
                            _self.addClass('favorite');
                            _self.find('span').html('收藏');
                        }
                        else if (_self.hasClass('favorite')) {
                            _self.removeClass('favorite');
                            _self.addClass('cancel_save');
                            _self.find('span').html('已收藏');
                        }
                    }
                }
                if (result.code === 0)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close(result.msg, 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    });
                }
            },
            error: function(result){
                if (result.status === 500)
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close('System error, please try again later', 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1);
                    });
                    return false;
                }
                if (result.status === 401)
                {
                    themes_obj.loginBox('index_type');
                    return false;
                }
                else if (result.status  === 403)
                {
                    themes_obj.upgradeBox('index_type');
                    return false;
                }
            }
        });
        if ($(this).hasClass('detail_url') || $(this).hasClass('detail_name_url') || $(this).hasClass('company_detail_url') || $(this).hasClass('focus_url'))
        {
            themes_obj.recordUserModel('Detail');
        }
    });
    function same_partner_fun(LId, CId)
    {

    }
    $('.content').on('click', '.view_partner', function()
    {
        var LId = $(this).attr('attr-LId');
        var CId = $(this).attr('attr-CId');
        global_obj.div_mask();
        $('.global_alert_box.alert_partner .detail_alert').html('<div class="no_data"><div class="loading_gif"></div></div>');
        $('.global_alert_box.alert_partner').addClass('cur');
        same_partner_fun(LId, CId)
    });
    $('.global_alert_box.alert_partner').on('click', '.close', function()
    {
        global_obj.div_mask(1);
        $('.global_alert_box.alert_partner').removeClass('cur')
    });
    // 已选选项点击关闭
    $('.new_select .has_choose .r_list').on('click', 'div.close', function()
    {
        if ($(this).attr('attr-flag') == 1)
        {
            $('#' + $(this).attr('attr-id')).click();
            has_choose_html();
        } else if ($(this).attr('attr-flag') == 2)
        {
            $('#banner .search form input[name=no_lock]').val('1');
            $('.main_con .left_side .filter_box .container .item #' + $(this).attr('attr-id')).attr("checked", false).parents('.item').removeClass('current');
            if ($(this).attr('attr-id') == 'ImportTimes4')
            {
                $('#filter_form #ImportTimes1').click();
            }
            filterSyncToAlert();
            $('.filter_form button[name=submit]').click()
            has_choose_html();
        }
        // 高级搜索已选项
        else if ($(this).attr('attr-flag') >= 3 && $(this).attr('attr-flag') <= 5) {

            if ($(this).attr('attr-name') === 'business_date') {
                $('input[name="' + $(this).attr('attr-name') + '"]').val('all');
                $('.business_date_val_text').html('所有日期');
            } else {
                $('input[name="' + $(this).attr('attr-name') + '"]').val('');
            }
            if ($(this).attr('attr-name') === 'business_country') {
                $('input[name="TradeCountry2"]').val('');
            }
            has_choose_html();
            list_fun();
        }
    });
    $('.new_thead .thead_sort').on('click', function()
    {
        if ($(this).find('.sort_list').is(':visible'))
        {
            $(this).find('.sort_list').hide()
        }
        else
        {
            $(this).find('.sort_list').show()
        }
        $("body").click(function(e)
        {
            var target = $(e.target);
            if (!target.parents().is('.sort_list') && !target.parents().is('.thead_sort'))
            {
                $(".sort_list").hide()
            }
        })
    });
    $(window).scroll(function()
    {
        $('.sort_list').hide()
    });
    $('body').on('click', '.middle_area .selector input[type=checkbox][name=select]', function()
    {
        box = $('body').find('.middle_area .selector_box');
        all = $('body').find('.middle_area .selector input[type=checkbox][name=select_all]');
        select = $('body').find('.middle_area .selector input[type=checkbox][name=select]');
        let text = lang_obj.clue.list.batch;
        let span = $('.selector input[type=checkbox][name=select_all]');
        if (select.is(':checked'))
        {
            span.parent().find('span').remove()
        }
        else
        {
            span.after("<span>" + text + "</span>")
        }
        checkedLength = $('.middle_area').find('.selector input[type=checkbox][name=select]:checked').length;
        checkedLength > 0 ? box.addClass('open') : box.removeClass('open');
        box.find('.tips span').text(checkedLength);
        checkedLength == select.length ? all.prop('checked', true) : all.prop('checked', false)
    });
    $('body').on('click', '.middle_area .selector input[type=checkbox][name=select_all]', function()
    {
        box = $('body').find('.middle_area .selector_box');
        all = $('body').find('.middle_area .selector input[type=checkbox][name=select_all]');
        select = $('body').find('.middle_area .selector input[type=checkbox][name=select]');
        let text = lang_obj.clue.list.batch;
        let span = $('.selector input[type=checkbox][name=select_all]');
        if (span.is(':checked'))
        {
            span.parent().find('span').remove()
        }
        else
        {
            $(this).after("<span>" + text + "</span>")
        }
        $(this).prop('checked') == true ? select.prop('checked', true) : select.prop('checked', false);
        $(this).prop('checked') == true ? box.addClass('open') : box.removeClass('open');
        checkedLength = $('.middle_area').find('.selector input[type=checkbox][name=select]:checked').length;
        box.find('.tips span').text(checkedLength)
    });
    let company_batch_save_timer = '';
    $('body').on('click', '.middle_area .new_thead .selector_box .save_collect', function()
    {
        if ($('#AccountId').val() == 0)
        {
            themes_obj.loginBox('list_batch_collect')
        }
        else
        {
            clearTimeout(company_batch_save_timer);
            company_batch_save_timer = setTimeout(function()
            {
                let cid = $('#CId').val();
                let this_size = 0;
                let this_val = ',';
                $('.middle_area .selector input[name="select"]').each(function()
                {
                    if ($(this).is(':checked'))
                    {
                        if ($(this).val())
                        {
                            this_size++;
                            this_val += $(this).val() + ','
                        }
                    }
                });
                if (this_size > 0)
                {
                    let seller_type = 'importer';
                    if (window.location.pathname === '/buyer')
                    {
                        seller_type = 'importer';
                    }
                    if (window.location.pathname === '/supplier')
                    {
                        seller_type = 'exporter';
                    }
                    $.ajax({
                        url: ajax_request_domain + '/customsCompany/customs_company_collect',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            seller_type: seller_type,
                            company_ids: this_val
                        },
                        beforeSend: (xhr) => {
                            xhr.setRequestHeader("token", getLocalStorage('token'));
                        },
                        success: function(result)
                        {
                            if (result.code === 1)
                            {
                                global_obj.win_alert_auto_close(result.msg, 'success', 2000, undefined, 0, function()
                                {
                                    window.location.reload();
                                });
                            }
                            else if (result.code === 0)
                            {
                                global_obj.div_mask();
                                global_obj.win_alert_auto_close(result.msg, 'fail', 2000, undefined, 0, function()
                                {
                                    global_obj.div_mask(1);
                                });
                            }
                            else
                            {
                                global_obj.div_mask();
                                global_obj.win_alert_auto_close(lang_obj.do_action.add_favorites_fail, 'fail', 2000, undefined, 0, function()
                                {
                                    global_obj.div_mask(1);
                                });
                            }
                        },
                        error: function(result){
                            if (result.status === 500)
                            {
                                global_obj.div_mask();
                                global_obj.win_alert_auto_close('System error, please try again later', 'fail', 2000, undefined, 0, function()
                                {
                                    global_obj.div_mask(1);
                                });
                                return false;
                            }
                            if (result.status === 401)
                            {
                                themes_obj.loginBox('index_type');
                                return false;
                            }
                            else if (result.status  === 403)
                            {
                                themes_obj.upgradeBox('index_type');
                                return false;
                            }
                        }
                    });
                }
                else
                {
                    global_obj.div_mask();
                    global_obj.win_alert_auto_close(lang_obj.do_action.add_favorites_fail, 'fail', 2000, undefined, 0, function()
                    {
                        global_obj.div_mask(1)
                    });
                }
            }, 500);
        }
        return false;
    });
    $('body').on('click', '.list_empty .consultant_box_new .btn_contact', function()
    {
        if (zuoooo_config.IsMobile)
        {
            $('body #nb_icon_wrap').click()
        }
        else
        {
            $('body #aff-im-root .embed-icon-default').click()
        }
    })
});
